package com.dl.base.utils

import com.google.gson.*
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

object GsonUtil {
    val gson: Gson by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
        val builder = GsonBuilder()
        builder.registerTypeAdapter(
            Int::class.java,
            JsonDeserializer { json: JsonElement, _: Type?, _: JsonDeserializationContext? -> json.asInt } as JsonDeserializer<Int>)
        builder.create()
    }

    fun <T> toJson(data: T): String {
        return gson.toJson(data)
    }

    fun <T> fromJson(data: String, clazz: Class<T>): T {
        return gson.fromJson(data, clazz)
    }

    inline fun <reified T> fromJson(data: String): T {
        return gson.fromJson(data, object : TypeToken<T>() {}.type)
    }
}